
import { defineConfig } from "vite"
import Vue from "@vitejs/plugin-vue"
import VueJsx from '@vitejs/plugin-vue-jsx'
import dts from "vite-plugin-dts"
import VueMacros from 'unplugin-vue-macros/vite'
import { fileURLToPath, URL } from 'node:url'

const config = {
  resolve: {
    alias: {
      '~': fileURLToPath(new URL('.', import.meta.url)),
      '@/src': fileURLToPath(new URL('./src', import.meta.url)),
      '@/packages': fileURLToPath(new URL('./packages', import.meta.url))
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler',
        // 静默 @import 弃用警告
        quietDeps: true,
        // 如果你项目中有全局的 scss 文件，可以继续在这里导入
        // additionalData: `@import "@/assets/styles/global.scss";`
      }
    }
  }
}
export default defineConfig(({ command, mode, ssrBuild }) => {
  if (command === 'serve') { // dev 独有配置
    return {
      plugins: [Vue(), VueJsx()],
      server: {
        port: 8088,
        host: '0.0.0.0',
      },
      ...config,
    }
  } else { // command === 'build' build 独有配置
    return {
      build: {
        outDir: "dist",
        lib: {
          entry: "./packages/index.js",
          name: "zk-content",
          fileName: (format) => {
            if (format === 'es') return 'es/index.js'
            if (format === 'cjs') return 'lib/index.js'
            return 'index.js'
          },
          formats: ["es", "cjs"],
        },
        rollupOptions: { // https://rollupjs.org/configuration-options/
          // 外部化（external）的模块在打包时不会被包含进去，而是在运行时从外部环境获取。globals选项就是用来映射这些外部模块的名称到全局变量的。
          external: ["vue", "@element-plus/icons-vue", "@wangeditor/editor-for-vue", "axios", "element-plus", "vue-router", "zhongke-content-component-vue3"],
          output: {
            globals: {
              vue: "Vue",
            },
            assetFileNames: (assetInfo) => {
              if (assetInfo.name && assetInfo.name.endsWith('.css')) {
                return 'theme/css/zk-content.css';
              }
              // 其他资源
              return 'theme/[name]-[hash][extname]';
            }
          },
        },
      },
      plugins: [
        VueMacros({
          setupComponent: false,
          setupSFC: false,
          plugins: {
            vue: Vue(),
            vueJsx: VueJsx(),
          },
        }),
        dts({
          tsConfigFilePath: "./tsconfig.json",
          outputDir: "dist/types",
        }),
      ],
      ...config,
    }
  }
})